<template>
  <!-- 修改用户对话框 -->
  <el-dialog title="修改用户" :visible.sync="editDialogVisible" width="50%" @close="editFormClose">
    <el-form :model="edituserinfo" :rules="editFormRules" ref="editFormRef" label-width="70px">
      <el-form-item label="用户名">
        <el-input v-model="edituserinfo.username" disabled></el-input>
      </el-form-item>
      <el-form-item label="邮箱" prop="email">
        <el-input v-model="edituserinfo.email"></el-input>
      </el-form-item>
      <el-form-item label="电话" prop="mobile">
        <el-input v-model="edituserinfo.mobile"></el-input>
      </el-form-item>
    </el-form>
    <span slot="footer" class="dialog-footer">
      <el-button @click="editDialogVisible = false">取 消</el-button>
      <el-button type="primary" @click="editUserData">确 定</el-button>
    </span>
  </el-dialog>
</template>
<script>
export default {
  props: {
    visible: {
      type: Boolean
    },
    //   修改用户信息表单数据
    edituserinfo: {
      type: Object
    }
  },
  data() {
    // 邮箱的验证方法
    var checkEmail = (rule, value, callback) => {
      const regEmail = /^\w+@\w+(\.\w+)+$/
      if (regEmail.test(value)) {
        return callback()
      }
      callback(new Error('请输入合法的邮箱'))
    }
    // 手机号验证方法
    var checkMobile = (rule, value, callback) => {
      const regMobile = /^1[34578]\d{9}$/
      if (regMobile.test(value)) {
        return callback()
      }
      callback(new Error('请输入合法的手机号'))
    }
    return {
      editDialogVisible: false,
      editFormRules: {
        email: [
          { required: true, message: '请输入邮箱', trigger: 'blur' },
          { validator: checkEmail, trigger: 'blur' }
        ],
        mobile: [
          { required: true, message: '请输入电话号', trigger: 'blur' },
          { validator: checkMobile, trigger: 'blur' }
        ]
      }
    }
  },
  methods: {
    // 修改用户数据对话框选择取消后重置表单
    editFormClose() {
      this.$refs.editFormRef.resetFields()
    },
    // 提交修改用户数据
    editUserData() {
      // 对提交的数据预校验
      this.$refs.editFormRef.validate(async valid => {
        if (!valid) return false
        const { data: res } = await this.$http.put(
          'users/' + this.edituserinfo.id,
          { email: this.edituserinfo.email, mobile: this.edituserinfo.mobile }
        )
        if (res.meta.status !== 200) {
          return this.$message.error('更新用户信息失败')
        }
        this.$message.success('更新用户信息成功')
        this.$emit('updateUsers')
        // this.getUserList()
        this.editDialogVisible = false
      })
    }
  },
  watch: {
    // 监听从父级传过来的visible属性传给addDialogVisible
    visible: function(val) {
      this.editDialogVisible = val
    },
    // 监听 当前页面的 dialog 的变化再传回给父级，否则父级一直是true
    editDialogVisible: function(val) {
      //   与async搭配使用 users使用:visible.async
      this.$emit('update:visible', val)
    }
  }
}
</script>
<style>
</style>
